<template>
<div>
    <form class="card comment-form" @submit.prevent="onAddComment">
                <div class="card-block">
            <textarea v-model="commentBody" class="form-control" placeholder="Write a comment..." rows="3"></textarea>
        </div>
        <div v-if="user" class="card-footer">
            <img :src="user.image" class="comment-author-img" />
            <button class="btn btn-sm btn-primary">
            Post Comment
            </button>
        </div>
        </form>
    
    <div class="card"
        v-for="comment in comments"
        :key="comment.id"
    >
        <div class="card-block">
            <p class="card-text">{{ comment.body }}</p>
        </div>
        <div class="card-footer">
            <nuxt-link :to="{name: 'profile', params: { username: comment.author.username }}" class="comment-author">
                <img :src="comment.author.image" class="comment-author-img" />
            </nuxt-link>
            &nbsp;
            <nuxt-link :to="{name: 'profile', params: { username: comment.author.username }}" class="comment-author">
                {{ comment.author.username }}
            </nuxt-link>
            <span class="date-posted">{{ comment.createdAt | date('MMM DD, YYYY') }}</span>
            <!-- 删除图标 -->
            <span class="mod-options" v-if="user.username === comment.author.username">
                <i class="ion-trash-a" @click="onDeleteComment(comment.id)"></i>
            </span>
        </div>
    </div>

</div>
</template>

<script>
import { getComments, addComment, deleteComment  } from '@/api/article'
import { mapState } from 'vuex'

export default {
    name: 'ArticleComments',
    props: {
        article: {
            type: Object,
            required: true
        }
    },
    data() {
        return {
            comments: [],
            commentBody: '',
        }
    },
    computed: {
        ...mapState(['user'])
    },
    async mounted() {
        const { data } = await getComments(this.article.slug)
        this.comments = data.comments
    },
    methods: {
        async onAddComment() {
            const commentBody = this.commentBody
            if (!commentBody.trim()) return // 判空

            const { data } = await addComment(this.article.slug, {
                comment: {
                    body: commentBody
                }
            })
            this.comments.unshift(data.comment)
        },
        async onDeleteComment(commentId) {
            try {
                await deleteComment(this.article.slug, commentId)
                this.comments.splice(this.comments.findIndex(comment => comment.id === commentId), 1)
            } catch (error) {
                // noop
            }
        }
    }
}
</script>

<style>

</style>